package com.goldcn.sys.service;

import com.goldcn.common.CommonUtils;
import com.goldcn.common.ResultData;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.util.IdGen;
import com.goldcn.sys.dao.SmsTemplateMapper;
import com.goldcn.sys.dao.SysConfigExtMapper;
import com.goldcn.sys.dao.SysConfigMapper;
import com.goldcn.sys.dto.InitCompanyDto;
import com.goldcn.sys.dto.SysConfigExtDto;
import com.goldcn.sys.dto.SysConfigRedisDto;
import com.goldcn.sys.model.SmsTemplate;
import com.goldcn.sys.model.SysConfig;
import com.goldcn.sys.model.SysConfigExt;
import com.goldcn.util.JsonUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Tim Peng
 * mail: lmn_022@163.com
 * Date: 2017/6/21
 * Time: 11:03
 * To change this template use File | Settings | File Templates.
 */
@Service
@Transactional
public class SysConfigService {
    @Autowired
    SysConfigMapper sysConfigMapper;

    @Autowired
    SysConfigExtMapper sysConfigExtMapper;

    @Autowired
    RestTemplate restTemplate;

  /*  @Autowired
    PropertiesConfig propertiesConfig;
*/
    @Autowired
    SmsTemplateMapper smsTemplateMapper;

    @Autowired
    RedisService redisService;

    public Object viewInfo(Long companyInfoID){


        List<Map<String,Object>> sysConfigExtList = sysConfigExtMapper.getMapByCompanyInfoID(companyInfoID,null);
        List<SmsTemplate> smsTemplateList = smsTemplateMapper.searchByCompanyInfoID(null,companyInfoID);
        Map<String,Object> sysConfig = sysConfigMapper.getMapByPrimaryKey(companyInfoID);

        Map<String,Object> jsonMap = JsonUtil.toMap(sysConfig.get("clazzPriceRate"));
        sysConfig.put("isClazzSupply",jsonMap.get("isClazzSupply"));
        sysConfig.put("cID",sysConfig.get("companyInfoID"));

        Map<String,Object> map = new HashMap();

        map.put("sysConfig",sysConfig);
        map.put("sysConfigExt",sysConfigExtList);
        map.put("smsTemplate",smsTemplateList);


        return map;
    }

    public Object addOrUpdate(Map<String,String> map) {
        Long companyInfoID = null == map.get("companyInfoID")? null :Long.valueOf(map.get("companyInfoID"));
        String sysConfig = map.get("sysConfig");
        JSONObject jsonobject = JSONObject.fromObject(sysConfig);
        // 公司信息
        SysConfig model = new SysConfig();
        model.setCompanyAccountCode(null == jsonobject.get("companyAccountCode")? null:jsonobject.getString("companyAccountCode"));
        if (null == companyInfoID){
            int i = sysConfigMapper.checkCompanyAccountCode(companyInfoID,model.getCompanyAccountCode());
            if(i>0){
                return new ResultData("1025","公司套账编码已被占用！");
            }
        }

        model.setLogo(null == jsonobject.get("logo")? null:jsonobject.getString("logo"));
        model.setBackgroundImg(null == jsonobject.get("backgroundImg")?null:jsonobject.getString("backgroundImg"));
        model.setShortName(CommonUtils.isNotEmpty(jsonobject.getString("shortName"))?jsonobject.getString("shortName"):null);
        model.setSystemName(CommonUtils.isNotEmpty(jsonobject.getString("systemName"))?jsonobject.getString("systemName"):null);
        model.setCopyright(CommonUtils.isNotEmpty(jsonobject.getString("copyright"))?jsonobject.getString("copyright"):null);
        model.setHotline(CommonUtils.isNotEmpty(jsonobject.getString("hotline"))?jsonobject.getString("hotline"):null);
        model.setIsOpenConsult(CommonUtils.isNotEmpty(jsonobject.getString("isOpenConsult"))?jsonobject.getString("isOpenConsult"):null);
        model.setIsOpenGoldPoint(CommonUtils.isNotEmpty(jsonobject.getString("isOpenGoldPoint"))?jsonobject.getString("isOpenGoldPoint"):null);
        /*model.setIsOpenLend(CommonUtils.isNotEmpty(jsonobject.getString("isOpenLend"))?jsonobject.getString("isOpenLend"):null);*/
        model.setOrderBorrowAuditLevel(CommonUtils.isNotEmpty(jsonobject.getString("orderBorrowAuditLevel"))?jsonobject.getString("orderBorrowAuditLevel"):null);
        model.setOrderBorrow(CommonUtils.isNotEmpty(jsonobject.getString("orderBorrow"))?jsonobject.getString("orderBorrow"):null);
        model.setVipPrice(CommonUtils.isNotEmpty(jsonobject.getString("vipPrice"))?jsonobject.getString("vipPrice"):null);
        model.setTempNO(CommonUtils.isNotEmpty(jsonobject.getString("tempNO"))?jsonobject.getString("tempNO"):null);
        model.setExclusiveService(CommonUtils.isNotEmpty(jsonobject.getString("exclusiveService"))?jsonobject.getString("exclusiveService"):null);
        model.setAboutus(CommonUtils.isNotEmpty(jsonobject.getString("aboutus"))?jsonobject.getString("aboutus"):null);
        model.setVipDesc(CommonUtils.isNotEmpty(jsonobject.getString("vipDesc"))?jsonobject.getString("vipDesc"):null);
        model.setWelcomeMessage(CommonUtils.isNotEmpty(jsonobject.getString("welcomeMessage"))?jsonobject.getString("welcomeMessage"):null);
        model.setGysName(CommonUtils.isNotEmpty(jsonobject.getString("gysName"))?jsonobject.getString("gysName"):null);
        model.setGysWelcomeMessage(CommonUtils.isNotEmpty(jsonobject.getString("gysWelcomeMessage"))?jsonobject.getString("gysWelcomeMessage"):null);
        model.setAppshareQR(null == jsonobject.get("appshareQR")?null:jsonobject.getString("appshareQR"));
        model.setIsOpenPointDeduction(CommonUtils.isNotEmpty(jsonobject.getString("isOpenPointDeduction"))?jsonobject.getString("isOpenPointDeduction"):null);
        model.setIsOpenPointWithdraw(CommonUtils.isNotEmpty(jsonobject.getString("isOpenPointWithdraw"))?jsonobject.getString("isOpenPointWithdraw"):null);
        model.setIsOpenPointWithdrawEntity(CommonUtils.isNotEmpty(jsonobject.getString("isOpenPointWithdrawEntity"))?jsonobject.getString("isOpenPointWithdrawEntity"):null);
        model.setPaymentSetting(CommonUtils.isNotEmpty(jsonobject.getString("paymentSetting"))?jsonobject.getString("paymentSetting"):null);
        model.setDeliverySetting(CommonUtils.isNotEmpty(jsonobject.getString("deliverySetting"))?jsonobject.getString("deliverySetting"):null);
        model.setInvoiceSetting(CommonUtils.isNotEmpty(jsonobject.getString("invoiceSetting"))?jsonobject.getString("invoiceSetting"):null);
       /*model.setIsOpenSupplierPayType(CommonUtils.isNotEmpty(jsonobject.getString("isOpenSupplierPayType"))?jsonobject.getString("isOpenSupplierPayType"):null);*/
        model.setIsOpenErp(CommonUtils.isNotEmpty(jsonobject.getString("isOpenErp"))?jsonobject.getString("isOpenErp"):null);
        model.setClazzPriceRate(CommonUtils.isNotEmpty(jsonobject.getString("clazzPriceRate"))?jsonobject.getString("clazzPriceRate"):null);
        if (null == companyInfoID){
            model.setCompanyInfoID(IdGen.get().nextId());
            sysConfigMapper.insertSelective(model);
            //初始化公司基础数据
            InitCompanyDto initCompanyDto =(InitCompanyDto) JSONObject.toBean(JSONObject.fromObject(map.get("initUserAccount")),InitCompanyDto.class);
            initCompanyDto.setCompanyID(model.getCompanyInfoID());
            //propertiesConfig.getBankBaseServiceURL()+
            ResultData resultData = restTemplate.postForObject("initConfig/initData", initCompanyDto, ResultData.class);
            if(!resultData.getData().equals(1)){
                throw new ServiceException("调用bankBase服务初始化数据接口出错", RestConst.ErrorCode.SERVICE_FAIL);
            }
            //初始化拓展信息
            //propertiesConfig.getPaymentCompanyID()
            List<SysConfigExt> list = sysConfigExtMapper.searchByCompanyInfoID(10000L);
            for (SysConfigExt ext : list){
                ext.setExtID(IdGen.get().nextId());
                ext.setCompanyInfoID(model.getCompanyInfoID());
            }
            sysConfigExtMapper.insertBatch(list);
        } else {
            model.setCompanyInfoID(companyInfoID);
            sysConfigMapper.updateByPrimaryKeySelective(model);
        }


        return new ResultData();
    }

    public Map selectAllCompany(Map<String,String> params) {
        //条件
        String shortName = params.get("shortName");
        String systemName = params.get("systemName");
        //分页
        int pageSize = Integer.parseInt(params.get("pageSize"));
        int pageIndex = Integer.parseInt(params.get("pageIndex"))*pageSize;
        String sortField = params.get("sortField");
        String sortOrder = params.get("sortOrder");
        String condition = "";
        if(CommonUtils.isNotEmpty(shortName)){
            condition = "and shortName like '%"+shortName+"%'";
        }
        if(CommonUtils.isNotEmpty(systemName)){
            condition += " and systemName like '%"+systemName+"%'";
        }
        int pageCount = sysConfigMapper.selectAllNum(condition);
        List<Map<String,Object>>  userList = sysConfigMapper.selectAllConfig(pageIndex,pageSize,condition,sortField,sortOrder);
        for (Map<String,Object> map : userList){
            map.put("cID",String.valueOf(map.get("companyInfoID")));
        }
        HashMap result = new HashMap();
        result.put("data", userList);
        result.put("total", pageCount);
        return result;
    }

    //查询全部公司数据，不分页
    public Object selectAllCompany_notPage() {
       List<SysConfig> list =  sysConfigMapper.selectAllConfig_notPage(null);
        return  list;
    }


    public Object updateExt(SysConfigExt ext) {
        SysConfig sysConfig = sysConfigMapper.selectByPrimaryKey(ext.getCompanyInfoID());
        if(null == sysConfig){
            ResultData resultData = new ResultData();
            resultData.setCode("125");
            return  resultData;
        }

        if(null == ext.getExtID()){
            ext.setAppEnabled(null == ext.getAppEnabled()?0:ext.getAppEnabled());
            ext.setAppEnabled(null == ext.getStartupEnabled()?0:ext.getStartupEnabled());
            ext.setExtID(IdGen.get().nextId());
            sysConfigExtMapper.insert(ext);
        }else{
            sysConfigExtMapper.updateByPrimaryKeySelective(ext);
        }
        //修改缓存
        updateRedisConfigExt(sysConfig.getCompanyInfoID());
        ResultData resultData = new ResultData();
        Map<String,Object> map = JsonUtil.toMap(ext);
        map.put("eID",String.valueOf(ext.getExtID()));
        resultData.setData(map);
        return resultData;
    }

    public Object updateExt(Map<String,String> map) {
        Long companyInfoID = null == map.get("companyInfoID")? null :Long.valueOf(map.get("companyInfoID"));
        SysConfig sysConfig = sysConfigMapper.selectByPrimaryKey(companyInfoID);
        if(null == sysConfig){
            ResultData resultData = new ResultData();
            resultData.setCode("125");
            return  resultData;
        }

        sysConfigExtMapper.deleteByCompanyInfoID(sysConfig.getCompanyInfoID());

        //拓展信息
        JSONArray extJArray = JSONArray.fromObject(map.get("extJson"));
        if(null != extJArray){
            List<SysConfigExt> list = new ArrayList();
            for (int i = 0; i < extJArray.size(); i++) {
                JSONObject item = extJArray.getJSONObject(i);
                if(item.size()==0||Strings.isBlank(item.get("code").toString())){
                    continue;
                }
                SysConfigExt ext = (SysConfigExt) JSONObject.toBean(item, SysConfigExt.class);
                ext.setExtID(IdGen.get().nextId());
                ext.setCompanyInfoID(Long.valueOf(sysConfig.getCompanyInfoID()));
                ext.setStartupEnabled(null==ext.getStartupEnabled()?0:ext.getStartupEnabled());
                ext.setAppEnabled(null==ext.getAppEnabled()?0:ext.getAppEnabled());
                ext.setSeq(i);
                ext.setAddTime(System.currentTimeMillis());
                ext.setUpdateTime(System.currentTimeMillis());
                list.add(ext);
            }
            if(list.size()>0){
                int i = sysConfigExtMapper.insertBatch(list);
            }
        }
        return new ResultData();
    }

    public Object updateMsgTemp(Map<String,String> map) {
        Long companyInfoID = null == map.get("companyInfoID")? null :Long.valueOf(map.get("companyInfoID"));
        SysConfig sysConfig = sysConfigMapper.selectByPrimaryKey(companyInfoID);
        if(null == sysConfig){
            ResultData resultData = new ResultData();
            resultData.setCode("125");
            return  resultData;
        }
        smsTemplateMapper.deleteByCompanyInfoID(sysConfig.getCompanyInfoID());//删除短信模板

        //短信模板
        JSONArray smsJArray = JSONArray.fromObject(map.get("smsJson"));
        if(null != smsJArray){
            List<SmsTemplate> list = new ArrayList();
            for (int i = 0; i < smsJArray.size(); i++) {
                JSONObject item = smsJArray.getJSONObject(i);
                if(item.size()==0||Strings.isBlank(item.get("smsTemplateCode").toString())){
                    continue;
                }
                SmsTemplate sms = (SmsTemplate) JSONObject.toBean(item, SmsTemplate.class);
                sms.setTemplateID(IdGen.get().nextId());
                sms.setCompanyInfoID(Long.valueOf(sysConfig.getCompanyInfoID()));
                sms.setSeq(i);
                sms.setAddTime(System.currentTimeMillis());
                sms.setUpdateTime(System.currentTimeMillis());
                list.add(sms);
            }
            if(list.size()>0){
                int i = smsTemplateMapper.insertBatch(list);
                return new ResultData();
            }
        }
        return new ResultData();
    }

    public Object updateEnabled(SysConfigExt ext,int flag){
        SysConfigExt configExt = sysConfigExtMapper.selectByPrimaryKey(ext.getExtID());
        if(null !=configExt){
            SysConfigExt model = new SysConfigExt();
            model.setExtID(ext.getExtID());
            if(flag==1){
                model.setStartupEnabled(ext.getStartupEnabled());
            }else{
                model.setAppEnabled(ext.getAppEnabled());
            }
            sysConfigExtMapper.updateByPrimaryKeySelective(model);
            //修改缓存
            updateRedisConfigExt(configExt.getCompanyInfoID());
            return new ResultData();
        }
        return new ResultData("1001","记录不存在，请先保存！");
    }


    public Object selectAllExtByCID(Long companyInfoID) {
        List<SysConfigExt> sysConfigExtList = sysConfigExtMapper.searchByCompanyInfoID(companyInfoID);
        Map<String,String>  map= new HashMap<>();
        for (SysConfigExt ext:sysConfigExtList) {
            map.put(ext.getCode().trim(),ext.getValue()==null?"":ext.getValue().trim());
        }
        ResultData<Map> result = new ResultData<>();
        result.setData(map);
        return result;
    }


    public Object selectTempByCode(Long companyInfoID,int type) {
        List<SmsTemplate> template = smsTemplateMapper.searchByCompanyInfoID(type,companyInfoID);
        if(template!=null && template.size()>0){
            SmsTemplate trimTemp = template.get(0);
            trimTemp.setSmsFreeSignName(trimTemp.getSmsFreeSignName()==null?"":trimTemp.getSmsFreeSignName().trim());
            trimTemp.setSmsTempContext(trimTemp.getSmsTempContext()==null?"":trimTemp.getSmsTempContext().trim());
            trimTemp.setSmsTemplateCode(trimTemp.getSmsTemplateCode()==null?"":trimTemp.getSmsTemplateCode().trim());
            trimTemp.setSmsTemplateName(trimTemp.getSmsTemplateName()==null?"":trimTemp.getSmsTemplateName().trim());
            return  new ResultData(trimTemp);
        }
        return new ResultData("0",null);
    }

    public Map<String,Object> getValByCode(Long companyInfoID,String code){
        return sysConfigExtMapper.getValByCode(companyInfoID,code);
    }

    public Object get(Long companyInfoID,String code){
        return sysConfigExtMapper.getValByCode(companyInfoID,code);
    }

    public String getString(Long companyInfoID,String code){
        return getRedisExt(companyInfoID,code);
    }

    public int getInt(Long companyInfoID,String code){
        String o = getRedisExt(companyInfoID,code);
        return null == o ? null: Integer.valueOf(o);
    }

    public boolean getBoolean(Long companyInfoID,String code){
        String o = getRedisExt(companyInfoID,code);
        return null == o ? null: Boolean.parseBoolean(o);
    }

    public Long getLong(Long companyInfoID,String code){
        String o = getRedisExt(companyInfoID,code);
        return null == o ? null: Long.valueOf(o);
    }

   public JSONArray getJSONArray(Long companyInfoID,String code){
       Map<String,Object> o = (Map<String,Object>)redisService.loadKey(String.valueOf(companyInfoID));
       JSONArray jsonArray = null == o.get("code") ?null :JSONArray.fromObject(o.get("code"));
       return jsonArray;
    }

    public String getRedisExt(Long companyID,String code){
        Map<String,Object> o = (Map<String,Object>)redisService.loadKey(String.valueOf(companyID));
        String values = null;
        if(o!=null && o.size()!=0 && o.get(code)!=null){
            values = o.get(code).toString();
        }else{
            Map<String,Object> map = sysConfigExtMapper.getValByCode(companyID,code);
            values = null==map.get("value")?null:map.get("value").toString();
        }
        return values;
    }

    public ResultData deleteExt(Long id){
        SysConfigExt ext = sysConfigExtMapper.selectByPrimaryKey(id);
        sysConfigExtMapper.deleteByPrimaryKey(ext.getExtID());
        //修改缓存
        updateRedisConfigExt(ext.getCompanyInfoID());
        return new ResultData();
    }

    public void setRedisConfigExt(){
        List<SysConfigRedisDto> extConfig = sysConfigExtMapper.getRedisMap(1);
        Map<String,Map<String,Object>> redisMap = new HashMap();
        for (SysConfigRedisDto dto : extConfig) {
            List<SysConfigExtDto> list = dto.getList();
            Map<String,Object> map = new HashMap();
            for (SysConfigExtDto ext : list){
                map.put(ext.getCode(),ext.getValue());
            }
            redisMap.put(String.valueOf(dto.getCompanyInfoID()),map);
        }
        for (Map.Entry<String,Map<String,Object>> entry : redisMap.entrySet()) {
            redisService.addOrUpdateRAS(entry.getKey(), entry.getValue(),2592000000L);
        }
    }

    public void updateRedisConfigExt(Long companyID){
        List<Map<String,Object>> map = sysConfigExtMapper.getMapByCompanyInfoID(companyID,1);
        Map<String,Object> redisMap = new HashMap();
        for (Map<String,Object> m : map){
            redisMap.put(m.get("code").toString(),m.get("value"));
        }
        redisService.addOrUpdateRAS(String.valueOf(companyID), redisMap,2592000000L);
    }
    /**查询app的配置信息
     * @Author tim peng
     * @Description
     * @param companyInfoID
     * @return
     * @Date 2017/8/14 15:12
     */
    public ResultData selectAllExtForApp(Long companyInfoID) {
        List<SysConfigExt> sysConfigExtList = sysConfigExtMapper.selectAllExtForApp(companyInfoID);
        Map<String,String>  map= new HashMap<>();
        for (SysConfigExt ext:sysConfigExtList) {
            map.put(ext.getCode().trim(),ext.getValue()==null?"":ext.getValue().trim());
        }
        ResultData<Map> result = new ResultData<>();
        result.setData(map);
        return result;
    }

    public Object selectAllExtForFtp(Long companyInfoID) {
        List<SysConfigExt> sysConfigExtList = sysConfigExtMapper.selectAllExtForApp(companyInfoID);
        Map<String,String>  map= new HashMap<>();
        for (SysConfigExt ext:sysConfigExtList) {
            map.put(ext.getCode().trim(),ext.getValue()==null?"":ext.getValue().trim());
        }

        return map;
    }

    public Object initAppExt(Long template,Long newCompanyID){
        List<SysConfigExt> sysConfigExtList = sysConfigExtMapper.selectAllExtForApp(template);
        for (SysConfigExt ext : sysConfigExtList){
            ext.setExtID(IdGen.get().nextId());
            ext.setAddTime(System.currentTimeMillis());
            ext.setUpdateTime(System.currentTimeMillis());
            ext.setCompanyInfoID(newCompanyID);
        }
        sysConfigExtMapper.insertBatch(sysConfigExtList);
        return new ResultData();
    }
}
